/**
 * Created by chocolate on 16/5/23.
 */

/**
 * 引入核心模块
 */
import React, {
  Component,
  StyleSheet,
  Text,
  TextInput,
  View,
  ScrollView,
  TouchableOpacity,
  Alert,
  DatePickerIOS,
  Picker,
  Modal,
} from 'react-native';

var PickerItem = Picker.Item;
/**
 * 引入Title模块
 * @type {Title}
 */
var Title = require('./Title');
var leaveQuery = require('./Query').query;
//var leaveQuery = new Query();

class LeaveScreen extends Component{

  /**
   * 构造函数
   * @param props
   */
  constructor(props){
    super(props);
    this.parent = this.props.parent;
    this.child = this.props.child;
    this.approverAccount = '张美艳';  //审批人的账号ID(手机号)
    this.state = {
        pickertype:0,         //0:type Picker;1:start DatePicker;2:end DatePicker
        reason:'',             //请假原因:0、病假;1、事假
        detail:'',
        startDate:null,
        endDate:null,
        timeZoneOffsetInHours: (-1) * (new Date()).getTimezoneOffset() / 60,
        modalVisible:false,
    }
    console.log("提交请假申请人手机号:"+this.props.parent.phone+"申请请假的小孩姓名:"+this.props.child.name);
  }

  /**
   * 点击Title"提交"按钮的响应函数
   * @private
   */
  _onPressSumbmit(){
    //Alert.alert('提示', '已经提交申请,等待班主任批准');
    leaveQuery.applyOneLeave(this.parent.phone,
                      this.child.id,
                      new Date().Format("yyyy-MM-dd hh:mm"),
                      this.state.reason,
                      this.state.startDate.Format("yyyy-MM-dd hh:mm"),
                      this.state.endDate.Format("yyyy-MM-dd hh:mm"),
                      this.state.detail,
                      this.approverAccount,
                      this,
                      function(owner,response){
                        if(response.success === true){
                          Alert.alert('提示', '已经提交申请,等待班主任批准',
                            [{text:'OK',onPress:()=>{owner._onPressReturn()}}]);
                        }});
  }

  /**
   * 点击Title"返回"按钮的响应函数
   * @private
   */
  _onPressReturn(){
    this.props.navigator.pop();
  }


  _setModalVisible(visible) {
    this.setState({modalVisible: visible});
  }
  /**
   * 点击请假类型
   * @private
   */
  _onPressLeaveType(){

    this.setState({pickertype:0});
    this.setState({modalVisible:true});
  }

  /**
   * 点击开始时间,弹出datePicker,关闭reason picker
   * @private
   */
  _onPressStartTime(){
    this.setState({pickertype:1});
    this.setState({modalVisible:true});
  }

  /**
   * 点击结束时间,淡出DatePicker,关闭reason picker
   * @private
   */
  _onPressEndTime(){
    this.setState({pickertype:2});
    this.setState({modalVisible:true});
  }

  _showPicker(){
    if(this.state.pickertype === 0){
      return(
          <Picker
              selectedValue={this.state.reason}
              mode={"dropdown"}
              onValueChange={(value) => this.setState({reason: value})}
              style={{marginTop:5,height:250,backgroundColor:'#FFF'}}>
              <PickerItem
                value={"病假"}
                label={"病假"}
              />
              <PickerItem
                value={"事假"}
                label={"事假"}
              />
            </Picker>
        )
    }
    else if(this.state.pickertype === 1){
      return(
        <DatePickerIOS
            style={{marginTop:5,height:250,backgroundColor:'#FFF'}}
            date={this.state.startDate===null?new Date():this.state.startDate}
            mode="datetime"
            minuteInterval={10}
            timeZoneOffsetInMinutes={this.state.timeZoneOffsetInHours * 60}
            onDateChange={this._onDateChange.bind(this)}
          />
      )
    }

   else if(this.state.pickertype === 2){
    return(
        <DatePickerIOS
          style={{marginTop:5,height:250,backgroundColor:'#FFF'}}
          date={this.state.endDate===null?new Date():this.state.endDate}
          mode="datetime"
          minuteInterval={10}
          timeZoneOffsetInMinutes={this.state.timeZoneOffsetInHours * 60}
          onDateChange={this._onDateChange.bind(this)}
        />
      )
    }
  }


  /**
   * 当选中时间,更新相应类型的时间
   * @param date
   * @private
   */
  _onDateChange(date){
    if(this.state.pickertype === 1){
      console.log("请假起始时间设置为:"+date.toLocaleString());
      this.setState({startDate: date});
    }
    else if(this.state.pickertype === 2){
      console.log("请假结束时间设置为:"+date.toLocaleString());
      this.setState({endDate: date});
    }
  }



  _dateTextTip(date){

    if(date === null) {
      return("请选择(必选) >");
    }
    else{
      return date.Format("yyyy-MM-dd hh:mm");
    }

  }

  _reasonTextTip(reason){
    if(reason === "") {
      return("请选择(必选) >");
    }
    else{
      return reason;
    }
  }



  /**
   * 本页面的渲染函数
   */
  render(){
    return(
      <ScrollView style = {styles.container}>
         <Modal
            animated={true}
            transparent={true}
            visible={this.state.modalVisible}
            onRequestClose={() => {this._setModalVisible(false)}}>
            <View  ref='modalContainer' style={styles.modalContainer}
                onStartShouldSetResponderCapture={(e) => {
        　　　　　　　　const target = e.nativeEvent.target;
        　　　　　　　　if (target === React.findNodeHandle(this.refs.modalContainer)) {
        　　　　　　　　　　this._setModalVisible(false);
        　　　　　　　　}
                }}>
               {this._showPicker()}
            </View>
        </Modal>

        <Title title={{left:"返回",center:(this.child.name+"的请假申请"),right:"提交",
                    leftAct:this._onPressReturn.bind(this),rightAct:this._onPressSumbmit.bind(this)}}></Title>

        <TouchableOpacity style={styles.flowRight} onPress={this._onPressLeaveType.bind(this)}>
          <Text style={[styles.buttonText,styles.leftSide]}>请假类型</Text>
          <Text style={[styles.buttonText,styles.rightSide]}>{this._reasonTextTip(this.state.reason)} </Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.flowRight} onPress={this._onPressStartTime.bind(this)}>
          <Text style={[styles.buttonText,styles.leftSide]}>开始时间</Text>
          <Text style={[styles.buttonText,styles.rightSide]}>{this._dateTextTip(this.state.startDate)} </Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.flowRight} onPress={this._onPressEndTime.bind(this)}>
          <Text style={[styles.buttonText,styles.leftSide]}>结束时间</Text>
          <Text style={[styles.buttonText,styles.rightSide]}>{this._dateTextTip(this.state.endDate)}</Text>
        </TouchableOpacity>

        <View style={[styles.flowRight,{height:150}]}>
          <Text style={[styles.buttonText,styles.leftSide]}>请假事由</Text>
          <TextInput
            style={{width:250}}
            placeholder = "请输入请假事由"
            onChangeText = {(text)=>{this.setState({detail:text})}}>
          </TextInput>
        </View>

        <View style={[styles.flowRight,{height:150}]}>
          <Text style={[styles.buttonText,styles.leftSide]}>审批人</Text>
          <TextInput
            style={{width:250}}
            placeholder = "选择头像可删除(必填)">
          
          </TextInput>
        </View>

      </ScrollView>
    )
  }

}


/**
 * 本模块的样式表
 * @type {*|{type, property}|{panHandlers}|ReactClass|Object|{duration, create, update}}
 */
const styles = StyleSheet.create({
  container: {
    backgroundColor:'#eee',
    flex:1,
  },
  modalContainer:{
    flex: 1,
    backgroundColor:'rgba(0, 0, 0, 0.5)',
    justifyContent:'flex-end',
  },
  flowRight:{
    alignSelf:'stretch',
    flexDirection: 'row', //水平排布
    alignItems: 'center', //中轴线对齐
    justifyContent: 'space-between',
    marginTop:10,
    backgroundColor:'#FFF',
    height:50,
  },
  buttonText:{
    fontSize:14,
  },
  leftSide:{
    marginLeft:20
  },
  rightSide:{
    marginRight:20,
  }
})

/**
 * 导出LeaveScreen类
 * @type {LeaveScreen}
 */
module.exports = LeaveScreen;